﻿ #include "tcp_client.h"
#include "qglobal.h"
#include <QThread>
#include <QTimer>
#include <QDir>
#include <QDataStream>
#include <QTcpSocket>
#include <QDateTime>

QString TcpClient::rawpath;  // 静态成员变量定义
QString TcpClient::wavepath;  // 静态成员变量定义
extern int countnum = 0;
TcpClient::TcpClient()
{
    TcpParaTypeDef* m_tcp_para = new TcpParaTypeDef;
    // QHostAddress address("192.168.2.101");
    m_tcp_para->ip ="127.0.0.1";
    m_tcp_para->port=8081;
    this->protocolParaInit(m_tcp_para);
    this->protocolOpen();
    //创建数据保存目录

    QString foldname1="WAVsound_data";
    QString foldname2="RAWsound_data";
    QString path_1="E:/ZM/cwh_down_protocol/UpwardPro";
    wavepath= path_1+ "/" + foldname1;
    rawpath=path_1 + "/" + foldname2;
    QDir dir;

    if (!dir.exists(wavepath)) {
        if (dir.mkpath(wavepath)) {
            qDebug() << "文件夹创建成功：" << wavepath;
        } else {
            qDebug() << "文件夹创建失败：" << wavepath;
        }
    }
    else {
        qDebug() << "文件夹已存在：" << wavepath;
        QDir dir2(rawpath);
        QFileInfoList fileList = dir2.entryInfoList(QDir::Files );
        foreach (const QFileInfo &fileInfo, fileList) {
            QFile file(fileInfo.absoluteFilePath());
            file.resize(0);



        }
    }










    if (!dir.exists(rawpath)) {
        if (dir.mkpath(rawpath)) {
            qDebug() << "文件夹创建成功：" << rawpath;
        }
        else {
            qDebug() << "文件夹创建失败：" << rawpath;
        }
    }
    else {
        qDebug() << "文件夹已存在：" << rawpath;
        QDir dir1(rawpath);
        QFileInfoList fileList = dir1.entryInfoList(QDir::Files );
        foreach (const QFileInfo &fileInfo, fileList) {
            QFile file(fileInfo.absoluteFilePath());

            file.resize(0);
        }
    }
}

TcpClient::~TcpClient()
{
    if (m_socket != nullptr) {
        qDebug() << "TcpSocket析构";

        m_socket->close();
        delete m_socket;
        m_socket = nullptr;
    }

    receiveDataCallback = nullptr;
}

int TcpClient::protocolParaInit(void* para_struct)
{
    TcpParaTypeDef* m_tcp_para = (TcpParaTypeDef*)para_struct;
    if (isIpCurrent(m_tcp_para->ip)) {
        qDebug() << "IP格式错误";
        return -1;
    }

    this->m_ip = m_tcp_para->ip;
    this->m_port = m_tcp_para->port;

    return 0;
}

int TcpClient::protocolOpen()
{
     if (m_socket == nullptr) {
        m_socket = new QTcpSocket();

    } else {
        qDebug() << "socket has been created";

    }
   // connect(m_socket, SIGNAL(error(QAbstractSocket::SocketError)),
    //        this, SLOT(onError(QAbstractSocket::SocketError)));

    m_socket->connectToHost(QHostAddress(this->m_ip), this->m_port); //套接字连接服务端

    connect(m_socket, &QTcpSocket::readyRead, this, &TcpClient::handleReceiveData_slot);
    Timersocket_failconnect=new QTimer;
    if (!m_socket->waitForConnected(50)) { // 等待连接成功
        // 连接失败
        qDebug() << "套接字连接失败";
        QTimer::singleShot(50,this,&TcpClient::protocolOpen);
        /*connect(m_socket, &QTcpSocket::disconnected, this, [=]() {
            qDebug() << "socket disconnect";
            connect(Timersocket_failconnect,&QTimer::timeout,this,&TcpClient::protocolOpen);
            Timersocket_failconnect->start(5);
        });*/
        return -1;

    }
    else{
        qDebug() << "连接成功";
        QThread* receiveThread = new QThread();
        bufAnalyse = new BufAnalyse();
        bufAnalyse->moveToThread(receiveThread);
        receiveThread->start();
        Timersocket_failconnect->deleteLater();

        connect(m_socket,&QTcpSocket::readyRead,this,&TcpClient::handleReceiveData_slot);
        connect(this, &TcpClient::bufDataAnalyseTimerStart_sig, bufAnalyse, &BufAnalyse::analyseTimerStart_slot);
        connect(this, &TcpClient::bufDataAnalyseTimerStop_sig, bufAnalyse, &BufAnalyse::analyseTimerStop_slot);



        //        connect(bufAnalyse, &BufAnalyse::parsed_data_sig, this, &TcpServer::sendDataToAnalyse_slot,Qt::BlockingQueuedConnection);

    }



    return 0;
}
void TcpClient::onError(QAbstractSocket::SocketError socketError) {
    qDebug() << "发生错误:" << m_socket->errorString();
}
int TcpClient::protocolClose()
{
    if (m_socket->state() == QAbstractSocket::UnconnectedState) {
        qDebug() << "套接字未连接";
        return -1;
    }

    m_socket->close();
    m_socket->deleteLater();
    m_socket = nullptr;

    return 0;
}

int TcpClient::protocolWrite(const QByteArray& data_buf)
{
    if (m_socket->write(data_buf) == -1) {
        qDebug() << "write error";
    }

    return 0;
}

void TcpClient::setProtocolReadCallbackFunc(ReceiveDataCallback callBackFunc)
{
    this->receiveDataCallback = callBackFunc;
}

bool TcpClient::isIpCurrent(const QString& ip)
{
    QHostAddress m_ip(ip);
    return m_ip.isNull();
}

void TcpClient::handleReceiveData_slot()//Receivedate
{  QByteArray data;
    data = m_socket->readAll();
    qDebug()<<"收到数据";
    connect(this,&TcpClient::receivedData_sig,bufAnalyse,&BufAnalyse::data_buf);
    emit receivedData_sig(data);
    if (first_analyse) {

        emit bufDataAnalyseTimerStart_sig(); // 分析线程定时器启动
        //analyseTimerStart_slot()
        bufDataAnalyse_timer = new QTimer(this);
        bufDataAnalyse_timer->setSingleShot(true);
        connect(bufDataAnalyse_timer, &QTimer::timeout, [=]() {
            // 没有新数据接收，停止分析线程定时器
            // connect(bufAnalyse,&BufAnalyse::port_buf_anafinish,this,[=]{
                emit bufDataAnalyseTimerStop_sig();
                qDebug()<<"数据停止";
            // });

            first_analyse = true;
            bufDataAnalyse_timer->deleteLater();

        });
    }


    first_analyse = false;
    bufDataAnalyse_timer->start(2000);

}
BufAnalyse::BufAnalyse(QObject *parent)
{

}

BufAnalyse::~BufAnalyse()
{
    delete buf_analyse_timer;

}
void BufAnalyse::dataClassification(QByteArray buf_data)
{  // qDebug()<<"数据分类";
    int sound_startIndex=buf_data.indexOf(("\x02\x01\x00\xFF\x55\x99\x88\xAA"));//数据开始索引,固定包头加版本号

    int frameStartIndex = -1;
    if (sound_startIndex != -1 && (frameStartIndex == -1 || sound_startIndex < frameStartIndex)) {
        frameStartIndex = sound_startIndex;}
    else{qDebug()<<"数据分类错误";}
    quint32 dataLength = static_cast<quint8>(buf_data[frameStartIndex  + 20]) << 24 |static_cast<quint8>((buf_data[frameStartIndex  + 19])) << 16|static_cast<quint8>(buf_data[frameStartIndex  + 18]) << 8| static_cast<quint8>(buf_data[frameStartIndex  + 17]);
    //int next_startIndex=frameStartIndex+26+dataLength;
    //QByteArray expected = QByteArray::fromHex("020100FF559988AA01");
    //if (buf_data.mid(next_startIndex, expected.size()) == expected) {
        // 字节数组匹配
    if(buf_data.size() >= dataLength+26){
        QByteArray frame;
        frame = port_buf.mid(frameStartIndex+26, dataLength);
        //qDebug()<<"33333";
        processTempData(frame);




    // 计算校验和
    /*quint64 fixstream=static_cast<quint8>(buf_data[frameStartIndex  + 7]) << 56 |static_cast<quint8>((buf_data[frameStartIndex  + 6])) << 48|static_cast<quint8>(buf_data[frameStartIndex  + 5]) << 40| static_cast<quint8>(buf_data[frameStartIndex  + 4])<< 36|static_cast<quint8>(buf_data[frameStartIndex  + 3]) << 24 |static_cast<quint8>((buf_data[frameStartIndex  + 2])) << 16|static_cast<quint8>(buf_data[frameStartIndex  + 1]) << 8| static_cast<quint8>(buf_data[frameStartIndex  ]);
    quint8  ver=static_cast<quint8>(buf_data[frameStartIndex  + 8]);//版本号
    quint32 fid=static_cast<quint8>(buf_data[frameStartIndex  + 12]) << 24 |static_cast<quint8>((buf_data[frameStartIndex  + 11])) << 16|static_cast<quint8>(buf_data[frameStartIndex  + 10]) << 8| static_cast<quint8>(buf_data[frameStartIndex  + 9]);
    quint32 frq=static_cast<quint8>(buf_data[frameStartIndex  + 16]) << 24 |static_cast<quint8>((buf_data[frameStartIndex  + 15])) << 16|static_cast<quint8>(buf_data[frameStartIndex  + 14]) << 8| static_cast<quint8>(buf_data[frameStartIndex  + 13]);
    quint32 dl=static_cast<quint8>(buf_data[frameStartIndex  + 20]) << 24 |static_cast<quint8>((buf_data[frameStartIndex  + 19])) << 16|static_cast<quint8>(buf_data[frameStartIndex  + 18]) << 8| static_cast<quint8>(buf_data[frameStartIndex  + 17]);
    quint32 r1=static_cast<quint8>(buf_data[frameStartIndex  + 24]) << 24 |static_cast<quint8>((buf_data[frameStartIndex  + 23])) << 16|static_cast<quint8>(buf_data[frameStartIndex  + 22]) << 8| static_cast<quint8>(buf_data[frameStartIndex  + 21]);
    int chk=(fixstream+ver+fid+frq+dl+r1)%255;*/
    // quint8 chk;
    }}
void BufAnalyse::data_buf(QByteArray buf_data){
    this->port_buf.append(buf_data);
    qDebug()<<port_buf.size();
};
void BufAnalyse::processTempData(QByteArray data)
{   Sounddate m_sounddate;//结构组储存数据,每次处理刷新
    int isenogh=0;
    //qDebug()<<"数据处理";
    int channel_number=8;//八通道
    int datalength=data.length();
    int n_singelsampingdatenum=datalength/channel_number;
    m_sounddate.sodatech1.append(data.mid(0,n_singelsampingdatenum));
    m_sounddate.sodatech2.append(data.mid(n_singelsampingdatenum*1,n_singelsampingdatenum));
    m_sounddate.sodatech3.append(data.mid(n_singelsampingdatenum*2,n_singelsampingdatenum));
    m_sounddate.sodatech4.append(data.mid(n_singelsampingdatenum*3,n_singelsampingdatenum));
    m_sounddate.sodatech5.append(data.mid(n_singelsampingdatenum*4,n_singelsampingdatenum));
    m_sounddate.sodatech6.append(data.mid(n_singelsampingdatenum*5,n_singelsampingdatenum));
    m_sounddate.sodatech7.append(data.mid(n_singelsampingdatenum*6,n_singelsampingdatenum));
    m_sounddate.sodatech8.append(data.mid(n_singelsampingdatenum*7,n_singelsampingdatenum));
    int countdates=m_sounddate.sodatech1.count()+m_sounddate.sodatech2.count()+m_sounddate.sodatech3.count()
                     +m_sounddate.sodatech4.count()+m_sounddate.sodatech5.count()+m_sounddate.sodatech6.count()+
                     m_sounddate.sodatech7.count()+ m_sounddate.sodatech8.count();
    /*if (countdates!=datalength/2){
        qDebug()<<"ProcessTemData Wrong";
    }*/

    QDir::setCurrent(TcpClient::rawpath);//
    for(int ii=1;ii<9;ii++){
        QString filename="rawdata";
        filename=filename+QString::number(ii)+".raw";
        QFile file(filename);
        if(file.open(QIODevice::ReadWrite | QIODevice::Text)){
            file.seek(file.size());
            QDataStream filestream(&file);
            filestream.setVersion(QDataStream::Qt_5_14);
            filestream.setByteOrder(QDataStream::LittleEndian);
            if(ii==1){filestream<<m_sounddate.sodatech1;if(file.size()>=48000*1*15*2){isenogh+=1;}}
            else if(ii==2){filestream<<m_sounddate.sodatech2;if(file.size()>=48000*1*15*2){isenogh+=1;}}
            else if(ii==3){filestream<<m_sounddate.sodatech3;if(file.size()>=48000*1*15*2){isenogh+=1;}}
            else if(ii==4){filestream<<m_sounddate.sodatech4;if(file.size()>=48000*1*15*2){isenogh+=1;}}
            else if(ii==5){filestream<<m_sounddate.sodatech5;if(file.size()>=48000*1*15*2){isenogh+=1;}}
            else if(ii==6){filestream<<m_sounddate.sodatech6;if(file.size()>=48000*1*15*2){isenogh+=1;}}
            else if(ii==7){filestream<<m_sounddate.sodatech7;if(file.size()>=48000*1*15*2){isenogh+=1;}}
            else if(ii==8){filestream<<m_sounddate.sodatech8;if(file.size()>=48000*1*15*2){isenogh+=1;}}
            if(isenogh>=8){

                connect(this,&BufAnalyse::rawdata_enough,this,&BufAnalyse::pcmtowave_slot);
                if(countnum==0){emit rawdata_enough();

                }
                else if(countnum ==1){
                    countnum=2;//防止没有转换完就刷新
                    emit rawdata_enough();

                }
            }



        }

    }
}
void BufAnalyse::analyseTimerStart_slot()
{qDebug()<<"111";
    buf_analyse_timer = new QTimer();
    connect(buf_analyse_timer, &QTimer::timeout, [=]() {

        int startIdx = port_buf.indexOf(frameStart);
        if (startIdx != -1 && port_buf.size() > startIdx + 2) {
            // 读取帧头后两个字节表示的长度（小端模式）
            quint32 dataLength = static_cast<quint8>(port_buf[startIdx + 20]) << 24 |static_cast<quint8>((port_buf[startIdx + 19])) << 16|static_cast<quint8>(port_buf[startIdx + 18]) << 8| static_cast<quint8>(port_buf[startIdx + 17]);
            int frameSize = 26+ dataLength;//一帧的总长度（帧头26）

            // 确保整个帧在缓冲区中
            if (port_buf.size() >=  frameSize) {
                QByteArray frameData = port_buf.mid(startIdx,frameSize);
                qDebug()<<frameData.size()<<"frameDate";

                qDebug()<<"发送到数据解析模块";
                connect(this,&BufAnalyse::parsed_data_sig,this,&BufAnalyse::dataClassification);
                emit parsed_data_sig(frameData); // 发送到数据解析模块
                port_buf.remove(0, frameSize);
                // if(port_buf.isEmpty()){
                //     emit port_buf_anafinish();

                // }
            }
        }

    });
    this->buf_analyse_timer->start(10);

}

void BufAnalyse::analyseTimerStop_slot()
{
    qDebug()<<"stop";
    this->buf_analyse_timer->stop();
    this->buf_analyse_timer->deleteLater();
}
void BufAnalyse::pcmtowave_slot(){
    //emit  storage_address(TcpClient::rawpath,TcpClient::wavepath);
    QDateTime currentDateTime = QDateTime::currentDateTime();
    QString currentTimeStr = currentDateTime.toString(("yyyy-MM-dd HH.mm.ss"));

    QString wavepath2=TcpClient::wavepath;

    wavepath2 = wavepath2 + "/" + currentTimeStr;
    QDir dir;
    if (!dir.exists(wavepath2)) {
        if (dir.mkpath(wavepath2)) {
            qDebug() << "文件夹创建成功：" << wavepath2;
        } else {
            qDebug() << "文件夹创建失败：" << wavepath2;
        }
    }
    else {
        qDebug() << "文件夹已存在：" << wavepath2;

    }

    for(int i=1;i<9;i++){
        QString wavepath1=TcpClient::wavepath +"/" + currentTimeStr;
        QString filename_W="wavdata";
        filename_W=filename_W+QString::number(i)+".wav";
        wavepath1 = wavepath1 + "/" +filename_W;

        QString PCMpath1=TcpClient::rawpath;
        QString filename_p="rawdata";
        filename_p=filename_p+QString::number(i)+".raw";
        PCMpath1 = PCMpath1 + "/" +filename_p;
        pcm_towav* Pcm_towav = new pcm_towav(wavepath1,PCMpath1,1,48000,16);//声道数1 采样率48K 16位

    }

    countnum = 1;
}
